<script lang="ts" setup>
import { FormInstance, Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { computed, onMounted, ref, shallowRef } from 'vue'
import { Ref } from 'vue'
import { PRIORITY_CONFIG, getTaskPriorityColor, getPriorityLabel } from '@/constants/Priority'
import { getMembersUsingGet, getProjectUsingGet } from '@/api/projectController'
import { editorConfig, editorStyle } from '@/composables/useEditorConfig'
import { IDomEditor } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { addBugUsingPost } from '@/api/bugController'

defineOptions({
  name: 'BugCreate'
})

const props = defineProps<{
  visible: boolean
  proId: number
}>()

const bugModalVisible = ref(false)
const emit = defineEmits(['reload', 'close', 'update:visible'])

// 缺陷表单数据
const addBugRequest: Ref<API.AddBugRequest> = ref({
  proId: undefined as number | undefined,
  mileId: undefined as number | undefined,
  iterId: undefined as number | undefined,
  reqId: undefined as number | undefined,
  taskId: undefined as number | undefined,
  ownerId: undefined as number | undefined,
  startTime: '',
  endTime: '',
  title: '',
  description: '',
  remark: '',
  priority: 0 // 设置默认优先级为 P0
})

const bugFormRef = ref<FormInstance | null>(null)

// 添加缺陷表单规则
const bugRules = {
  title: [
    { required: true, message: '请输入缺陷标题' },
    { maxLength: 50, message: '标题最多50个字符' }
  ],
  priority: [{ required: true, message: '请选择优先级' }],
  ownerId: [{ required: true, message: '请选择负责人' }],
  startTime: [{ required: true, message: '请选择开始时间' }],
  endTime: [{ required: true, message: '请选择结束时间' }]
}

const handleSubmitBug = async () => {
  try {
    //校验时间选择
    addBugRequest.value.proId = props.proId
    if (dayjs(addBugRequest.value.startTime).isAfter(dayjs(addBugRequest.value.endTime))) {
      Message.error('开始时间不能晚于结束时间')
      return false
    }

    if (!bugFormRef.value) return false
    const errors = await bugFormRef.value.validate()
    if (errors) {
      Message.error('请填写完整信息')
      return false
    }

    // 验证通过后再格式化时间
    const formattedStartTime = dayjs(addBugRequest.value.startTime).format('YYYY-MM-DDTHH:mm:ss')
    const formattedEndTime = dayjs(addBugRequest.value.endTime).format('YYYY-MM-DDTHH:mm:ss')

    // 创建新的请求对象，避免修改原始数据
    const submitData = {
      ...addBugRequest.value,
      startTime: formattedStartTime,
      endTime: formattedEndTime
    }

    // 调用添加缺陷接口
    const res: any = await addBugUsingPost(submitData)
    if (res.code === 0) {
      Message.success('创建缺陷成功')
      bugModalVisible.value = false
      emit('reload', true)
      return true
    } else {
      Message.error(res.message || '创建缺陷失败')
      return false
    }
  } catch (error) {
    console.error('创建缺陷失败:', error)
    return false
  }
}

// 编辑器相关
const bugDescriptionEditor = shallowRef()
const bugRemarkEditor = shallowRef()

// 在弹窗关闭时清理编辑器实例
const handleBugModalClose = () => {
  if (bugDescriptionEditor.value) {
    bugDescriptionEditor.value.destroy()
    bugDescriptionEditor.value = null
  }
  if (bugRemarkEditor.value) {
    bugRemarkEditor.value.destroy()
    bugRemarkEditor.value = null
  }
  emit('close')
}

// 获取项目成员
const projectMembers = ref<API.UserInProjectVo[]>([])

// 缺陷日期禁用函数
const disabledBugDate = (date: Date) => {
  return dayjs(date).isBefore(dayjs(), 'day')
}

// 获取项目信息
const currentProject = ref<API.ProjectVo>()
const milestones = ref<API.MileStoneVo[]>([])

const getCurrentProject = async () => {
  try {
    const res: any = await getProjectUsingGet({
      id: props.proId
    })
    if (res.code === 0) {
      currentProject.value = res.data
      milestones.value = currentProject.value?.mileStoneVoList || []
      projectMembers.value = currentProject.value?.members || []
    } else {
      Message.error(res.msg || '获取项目信息失败')
    }
  } catch (error) {
    console.error('获取项目信息失败:', error)
    Message.error('获取项目信息失败')
  }
}

// 选择关联项处理函数
const handleMilestoneSelect = (id: number | undefined) => {
  addBugRequest.value.mileId = id
  if (!id) {
    addBugRequest.value.iterId = undefined
    addBugRequest.value.reqId = undefined
    addBugRequest.value.taskId = undefined
  }
}

const handleIterationSelect = (id: number | undefined) => {
  addBugRequest.value.iterId = id
  if (!id) {
    addBugRequest.value.reqId = undefined
    addBugRequest.value.taskId = undefined
  }
}

const handleRequirementSelect = (id: number | undefined) => {
  addBugRequest.value.reqId = id
  if (!id) {
    addBugRequest.value.taskId = undefined
  }
}

const handleTaskSelect = (id: number | undefined) => {
  addBugRequest.value.taskId = id
}

// 计算选项
const milestoneOptions = computed(() =>
  milestones.value.map((milestone: API.MileStoneVo) => ({
    label: milestone.title,
    value: milestone.id
  }))
)

const iterationOptions = computed(() => {
  if (addBugRequest.value.mileId) {
    const milestone = milestones.value.find((m) => m.id === addBugRequest.value.mileId)
    return (
      milestone?.iterationVoList?.map((iteration) => ({
        label: iteration.title,
        value: iteration.id
      })) || []
    )
  }
  return (milestones.value || []).flatMap(
    (milestone) =>
      milestone.iterationVoList?.map((iterationVo) => ({
        label: iterationVo.title,
        value: iterationVo.id
      })) || []
  )
})

const requirementOptions = computed(() => {
  if (addBugRequest.value.iterId) {
    const iteration = (milestones.value || [])
      .flatMap((m) => m.iterationVoList || [])
      .find((i) => i.id === addBugRequest.value.iterId)
    return (
      iteration?.requirementVoList?.map((requirementVo) => ({
        label: requirementVo.title,
        value: requirementVo.id
      })) || []
    )
  }
  return (milestones.value || []).flatMap(
    (milestone) =>
      milestone.iterationVoList?.flatMap(
        (iterationVo) =>
          iterationVo.requirementVoList?.map((requirementVo) => ({
            label: requirementVo.title,
            value: requirementVo.id
          })) || []
      ) || []
  )
})

const taskOptions = computed(() => {
  if (addBugRequest.value.reqId) {
    const requirement = (milestones.value || [])
      .flatMap((m) => m.iterationVoList || [])
      .flatMap((i) => i.requirementVoList || [])
      .find((r) => r.id === addBugRequest.value.reqId)
    return (
      requirement?.taskVoList?.map((taskVo) => ({
        label: taskVo.title,
        value: taskVo.id
      })) || []
    )
  }
  return (milestones.value || []).flatMap(
    (milestone) =>
      milestone.iterationVoList?.flatMap(
        (iterationVo) =>
          iterationVo.requirementVoList?.flatMap(
            (requirementVo) =>
              requirementVo.taskVoList?.map((taskVo) => ({
                label: taskVo.title,
                value: taskVo.id
              })) || []
          ) || []
      ) || []
  )
})

const initStartDate = ref(currentProject.value?.startTime || '')
const initEndDate = ref(currentProject.value?.endTime || '')

const formatDateTime = (time: string | Date | null) => {
  if (!time) return null
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 时间变更处理函数
const handleBugTimeChange = (type: 'start' | 'end', value: string | null) => {
  const formattedValue = formatDateTime(value)

  if (!value) {
    Message.warning(`请选择${type === 'start' ? '开始' : '结束'}时间`)
    return false
  }

  if (type === 'start') {
    addBugRequest.value.startTime = formattedValue || ''
  } else {
    if (dayjs(value).isBefore(dayjs(addBugRequest.value.startTime))) {
      Message.warning('结束时间不能早于开始时间')
      return false
    }
    addBugRequest.value.endTime = formattedValue || ''
  }
  return true
}

// 编辑器创建处理函数
const handleDescriptionEditorCreated = (editor: IDomEditor) => {
  if (bugDescriptionEditor.value) {
    bugDescriptionEditor.value.destroy()
  }
  bugDescriptionEditor.value = editor
}

const handleRemarkEditorCreated = (editor: IDomEditor) => {
  if (bugRemarkEditor.value) {
    bugRemarkEditor.value.destroy()
  }
  bugRemarkEditor.value = editor
}

onMounted(async () => {
  bugModalVisible.value = props.visible
  await getCurrentProject()
})
</script>

<template>
  <a-modal
    v-model:visible="bugModalVisible"
    @update:visible="(val) => emit('update:visible', val)"
    title="新建缺陷"
    @cancel="handleBugModalClose"
    @before-ok="handleSubmitBug"
    modal-class="bug-modal"
    width="auto"
    :draggable="true"
    id="bug-create"
  >
    <a-form
      ref="bugFormRef"
      :model="addBugRequest"
      :rules="bugRules"
      layout="vertical"
      class="bug-form"
    >
      <!-- 标题 -->
      <a-form-item field="title" label="缺陷标题" validate-trigger="blur">
        <a-input v-model="addBugRequest.title" placeholder="请输入缺陷标题" allow-clear />
      </a-form-item>

      <!-- 优先级和负责人 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="priority" label="优先级" validate-trigger="change">
            <a-select v-model="addBugRequest.priority" placeholder="请选择优先级">
              <a-option :value="PRIORITY_CONFIG.P0.value">
                <span :style="{ color: PRIORITY_CONFIG.P0.color }">{{
                  PRIORITY_CONFIG.P0.label
                }}</span>
                - {{ PRIORITY_CONFIG.P0.description }}
              </a-option>
              <a-option :value="PRIORITY_CONFIG.P1.value">
                <span :style="{ color: PRIORITY_CONFIG.P1.color }">{{
                  PRIORITY_CONFIG.P1.label
                }}</span>
                - {{ PRIORITY_CONFIG.P1.description }}
              </a-option>
              <a-option :value="PRIORITY_CONFIG.P2.value">
                <span :style="{ color: PRIORITY_CONFIG.P2.color }">{{
                  PRIORITY_CONFIG.P2.label
                }}</span>
                - {{ PRIORITY_CONFIG.P2.description }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="ownerId" label="负责人">
            <a-select v-model="addBugRequest.ownerId" placeholder="请选择负责人">
              <a-option v-for="member in projectMembers" :key="member.id" :value="member.id">
                {{ member.name + `(` + member.username + `)` }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 时间选择 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="startTime" label="开始时间">
            <a-date-picker
              v-model="addBugRequest.startTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择开始时间"
              style="width: 100%"
              :disabled-date="disabledBugDate"
              :default-value="initStartDate"
              @change="(value) => handleBugTimeChange('start', value)"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="endTime" label="结束时间">
            <a-date-picker
              v-model="addBugRequest.endTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择结束时间"
              style="width: 100%"
              :disabled-date="disabledBugDate"
              :default-value="initEndDate"
              @change="(value) => handleBugTimeChange('end', value)"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 关联选择项 -->
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item field="mileId" label="关联里程碑">
            <a-select
              v-model="addBugRequest.mileId"
              placeholder="请选择里程碑"
              allow-clear
              @change="handleMilestoneSelect"
            >
              <a-option
                v-for="option in milestoneOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="iterId" label="关联迭代">
            <a-select
              v-model="addBugRequest.iterId"
              placeholder="请选择迭代"
              allow-clear
              @change="handleIterationSelect"
              :disabled="!addBugRequest.mileId"
            >
              <a-option
                v-for="option in iterationOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="reqId" label="关联需求">
            <a-select
              v-model="addBugRequest.reqId"
              placeholder="请选择需求"
              allow-clear
              @change="handleRequirementSelect"
              :disabled="!addBugRequest.iterId"
            >
              <a-option
                v-for="option in requirementOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="taskId" label="关联任务">
            <a-select
              v-model="addBugRequest.taskId"
              placeholder="请选择任务"
              allow-clear
              @change="handleTaskSelect"
              :disabled="!addBugRequest.reqId"
            >
              <a-option
                v-for="option in taskOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 描述编辑器 -->
      <a-form-item field="description" label="描述">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid var(--color-border)"
            :editor="bugDescriptionEditor"
            mode="default"
          />
          <Editor
            v-model="addBugRequest.description"
            :default-config="editorConfig"
            :style="editorStyle"
            mode="default"
            v-if="props.visible"
            @on-created="handleDescriptionEditorCreated"
          />
        </div>
      </a-form-item>

      <!-- 备注编辑器 -->
      <a-form-item field="remark" label="备注">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid var(--color-border)"
            :editor="bugRemarkEditor"
            mode="default"
          />
          <Editor
            v-model="addBugRequest.remark"
            :default-config="editorConfig"
            :style="editorStyle"
            mode="default"
            v-if="props.visible"
            @on-created="handleRemarkEditorCreated"
          />
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
.bug-modal {
  min-width: 800px;
  max-width: 1200px;
}

.editor-container {
  border: 1px solid var(--color-border);
  border-radius: 4px;
}

:deep(.w-e-text-container) {
  min-height: 200px;
  max-height: 500px;
  overflow-y: auto;
}
</style>
